import { Component,OnInit } from '@angular/core';
import {Store,Select} from '@ngxs/store';
import {SetNav,UserGuidState,SetRoster,SetBackgroundVaried} from '../app.state';
import {Observable} from 'rxjs';
import {RollService} from '../my-service/roll.service';
import {UtilService} from '../my-service/util.service';
import { Router} from '@angular/router';
@Component({
  selector: 'app-roster',
  templateUrl: './roster.component.html',
  styleUrls: ['./roster.component.css']
})
export class RosterComponent implements OnInit  {
  @Select(UserGuidState) userGuid$: Observable<any>; //获取用户guid和登录状态
  userGuid:string;
  readImg:string;
  haveRoster=false;
  classList=[
    { ClassName:'',
      CreateTime:'',
      EndTime:'',
      Creator:'',
      Number:0,}
  ]; //加入班级列表
  constructor(
    private store:Store,
    private rollService:RollService,
    private utilService:UtilService,
    private route:Router
  ) {
    this.store.dispatch(new SetNav('roster'));
    this.store.dispatch(new SetBackgroundVaried(false));
    this.readImg = this.utilService.readImgUrl;
    this.userGuid$.subscribe(res=>{
      this.userGuid=res.userGuid;
    })
  }
  ngOnInit(){
   //获取已经加入班级列表
   this.rollService.getJoinClass(this.userGuid).then(res=>{
     if(res.status==1){
        if(res.data[0]){
          let classList = '';
          this.haveRoster=true;
           res.data.forEach((item,index)=>{
             if(index!==res.data.length-1){
               classList+='"'+item.FK_ClassGuid+'"'+',';
             }else {
               classList+='"'+item.FK_ClassGuid+'"'
             }
           });
          //获取所有加入的班级
          this.rollService.getClassList(classList).then(res=>{
             if(res.status==1){
               //过滤掉已经过期的班级
               if(res.data[0]){
                 for(let i =0;i<res.data.length;i++){
                   res.data[i].CreateTime = this.utilService.changDateString(res.data[i].CreateTime).slice(0,10);
                   res.data[i].EndTime = this.utilService.changDateString(res.data[i].EndTime).slice(0,10);
                   if( res.data[i].State==1){
                     //已经过期或者被删除
                     res.data.splice(i,1);
                   }
                 }
               }
               this.classList = res.data;
             }
          })
        }
     }
   })
  }
  // 去到花名册详情页
  goRosterInfo(roster){
    this.store.dispatch(new SetRoster(roster.PK_ClassGuid,roster.ClassName));
    this.route.navigate(['/home/rosterInfo',roster.PK_ClassGuid]);
  }
}
